package com.padgett.resourcemanagement.client;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;
import com.padgett.resourcemanagement.util.DateUtil;

/**
 * Search personal clients by keyword that matches both first name and last name.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class AjaxSearchPersonalClientNameServlet extends HttpServlet{
	private static final Logger logger=Logger.getLogger(AjaxSearchPersonalClientNameServlet.class.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		String keywordString=req.getParameter("keywords");
		long startTime=System.currentTimeMillis();
		String[] keywords=keywordString.split(" ");
		List<Entity> entities=new ArrayList<Entity>();
		List<Entity> clientNames=ClientDAO.getPersonalClients();
		for(Entity client:clientNames){
			for(String keyword:keywords){
				if(((String)client.getProperty("NameSearch")).contains(keyword.toLowerCase())){
					entities.add(client);
					break;
				}
			}
		}
		
		long stopTime=System.currentTimeMillis();
		System.out.println("Total entities:"+entities.size()+". Total search time:"+((stopTime-startTime)/1000)+"s");
		JSONObject response=new JSONObject();
		String errorResponse=null;
		try {
			response.put("success",true);
			response.put("size",entities.size());
			List<JSONObject> clients=new ArrayList<JSONObject>();
			Iterator<Entry<String, Object>> iterator=null;
			for(Entity entity:entities){
				JSONObject client=new JSONObject();
				client.put("clientId", KeyFactory.keyToString(entity.getKey()));
				iterator=entity.getProperties().entrySet().iterator();
				while(iterator.hasNext()){
					Map.Entry<String, Object> entry=(Map.Entry<String, Object>)iterator.next();
					if(entry.getValue() instanceof Date){
						client.put(entry.getKey(), DateUtil.formatDate(((Date)entry.getValue()), DateUtil.LONG_DATE_FORMAT));
					}else if(entry.getValue() instanceof Text){
						client.put(entry.getKey(), ((Text)entry.getValue()).toString());
					}else{
						client.put(entry.getKey(), entry.getValue());
					}
				}
				clients.add(client);
			}
			response.put("data", clients);
		} catch (JSONException e) {
			logger.severe(e.getMessage());
			e.printStackTrace();
			errorResponse="{\"success\":false,\"error\":\""+e.getMessage()+"\"}";
		}
		if(errorResponse!=null){
			resp.getWriter().write(errorResponse);
		}else{
			resp.getWriter().write(response.toString());
		}
	}
}
